#!/bin/env python
#-*-coding:utf-8-*-

import MySQLdb
import string
import sys 
reload(sys) 
sys.setdefaultencoding('utf8')
import ConfigParser

def get_threads(conn):
    try:
        curs=conn.cursor()
        curs.execute("select * from processlist;");
        return curs.fetchall()

    except Exception,e:
        return null    
        print e

    finally:
        curs.close()


def get_threads_running(conn):
    try:
        curs=conn.cursor()
        curs.execute("select * from processlist where db is not null and db != 'information_schema' and  command !='Sleep';");
        return curs.fetchall()

    except Exception,e:
        return null
        print e

    finally:
        curs.close()

def get_threads_waits(conn):
    try:
        curs=conn.cursor()
        curs.execute("select * from processlist where db is not null and db != 'information_schema' and  command !='Sleep' and time > 3;");
        return curs.fetchall()

    except Exception,e:
        return null
        print e

    finally:
        curs.close()


def format_threads_table(data):
    table_header = "<table border=1 style='font-size:12px;color:#333333;border-width:1px;border-color:#666666;'>"
    content = "<tr><td>HOST</td><td>USER</td><td>DB</td><td>COMMAND</td><td>TIME</td><td>STATE</td><td>INFO</td></tr>"
    for item in data:
       id = item[0]
       user = item[1]
       host = item[2]
       db = item[3]
       command = item[4]
       time = str(item[5])
       state = item[6]
       info = item[7]
       if db is not None and command is not None :
          if state is None:
             state = ''
          if info is None:
             info = '' 
          content = content+"<tr><td>"+host+"</td><td>"+user+"</td><td>"+db+"</td><td>"+command+"</td><td>"+time+"</td><td>"+state+"</td><td>"+info+"</td></tr>"
    table_footer = "</table>"
    table = table_header+content+table_footer
    return table
